package com.road.vast.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @Author 郭泽鹏
 * @Date 2020/7/30 13:35
 * @Version 1.0
 * @Description token的创建和解析
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JwtUtils {
    //签名私钥
    private String key;
    //失效时间
    private long ttl;

    /**
     * 设置认证token
     * @param id：登录用户id
     * @param name：登录用户名
     * @param map
     * @return
     */
    public String createJWT(String id, String name, Map<String, Object> map){
        //设置失效时间
        long now = System.currentTimeMillis();  //当前毫秒
        long exp = now + ttl;
        //创建JwtBuilder
        JwtBuilder jwtBuilder = Jwts.builder().setId(id)
                .setSubject(name)
                .setIssuedAt(new Date())
                //设置签名的加密算法和私钥
                .signWith(SignatureAlgorithm.HS256, key);
        //根据map设置claims
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            jwtBuilder.claim(entry.getKey(), entry.getValue());
        }
        //设置失效时间
        jwtBuilder.setExpiration(new Date(exp));
        //创建token
        String token = jwtBuilder.compact();
        return token;
    }

    /**
     * 解析token字符串
     */
    public Claims parseJwt(String token){
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return claims;
    }
}
